window.app = angular.module("book", ['ngSanitize'])
    .controller('bookController', ['$http', '$scope', '$timeout','$interval',function ($http, $scope, $timeout,$interval) {
        window.$scope = $scope;
        $scope.selected = window['selected'];   //单程时为选中舱位下标，往返时为返程舱位下标
        $scope.pay_base_url = window['pay_base_url'];
        $scope.uid = window['uid'];

        $scope.departCity = window['departCity'];
        $scope.departCode = window['departCode'];
        $scope.destCity = window['destCity'];
        $scope.destCode = window['destCode'];
        $scope.type = window['type'];
        $scope.otaId = window['otaId'];
        $scope.departDate = window['departDate'];
        $scope.destDate = window['destDate'];
        $scope.comeFrom = window['comeFrom'];
        $scope.couponDefault = angular.fromJson(window['couponDefault']);
        $scope.idTypeList = angular.fromJson(window['idTypeList']);
        $scope.psgerTypeName = {'1': '成人', '2': '儿童'};
        $scope.psgerSexName = {'1': '男', '2': '女'};
        $scope.order_total_price = 0;

        $scope.supportChildren = true;
        $scope.seat_go_selected = localStorage.getItem('seat_go_selected'); //往返去程舱位下标
        $scope.seat_result_go = angular.fromJson(localStorage.getItem('seat_infos_go'));
        $scope.bGoBackList = false;
        $scope.containAccidentInsure = false;
        $scope.containDelayInsure = false;
        $scope.needInvoice = false;
        $scope.tmpid = 0;

        $scope.showPsgerList = $scope.psgerList = [];   //uid下全部乘机人列表
        $scope.psgerResultList = [];
        $scope.psgerChildNums = 0;//选中乘机人列表
        $scope.showBuyerList = $scope.buyerList = [];   //uid下全部联系人列表

        // 邮寄行程单/发票费用 @朱丽莉 2019.03.18修改
        $scope.invoicePrice = 20;

        // 保险隐藏
        $scope.insuranceShow = true;

        $scope.idTypeName = {};
        angular.forEach($scope.idTypeList, function(idtypeItem){
            $scope.idTypeName[idtypeItem.id_type] = idtypeItem.id_type_name;
        });

        $scope.buyer = {    //选中联系人
            buyer_id: "",
            buyer_name: "",
            buyer_phone: "",
            buyer_email: ""
        };

        $scope.invoice_info = {
            title: "",
            tax_number: "",
            name: "",
            addr: "",
            invoice_type: 0
        };
        $scope.inner = {
            is_busi_inner: -1,
            busi_inner_desc: ''
        };

        $scope.showEmptyCouponView = false;
        $scope.selectedCoupon = {
            use : false,
            coupon_id: "",
            coupon_code: "",
            cond_price: "",
            discount_type: "",
            discount_value: "",
            discount_max_value:"",
            used_condition_price: 0
        };
        $scope.input_coupon_code = '';
        //临时下掉验证码
        $scope.timeoutValidaeMobile = null;
        $scope.$watch('buyer.buyer_phone',function(){
            $timeout.cancel($scope.timeoutValidaeMobile);
            $scope.timeoutValidaeMobile = $timeout($scope.validateMobile,1000);
        });

        $scope.validateMobile = function(){
            var data = {
                after_style: 'default',
                update: {
                    action: 'validate_mobile',
                    mobile:$scope.buyer.buyer_phone,
                    phone_country:'86'
                }
            };
            $http({
                method: "post",
                url: "/flight/rest/contacts/",
                data: $.param(data),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function (res) {
                $scope.mobile_is_validated = res.data.is_validated;
                if ($scope.mobile_is_validated == 0) {
                    $scope.auth_code_div = true;
                    if($scope.show_send_button == false && $scope.show_timeout_info ==true ){
                        return ;
                    }
                    $scope.show_send_button = true;
                    $scope.show_timeout_info = false;
                }else{
                    $scope.auth_code_div = false;
                    $scope.show_send_button = false;
                    $scope.show_timeout_info = false;
                }
            });
        }

        $scope.sendAuthCode = function () {
            $scope.buyer.buyer_phone_country = $('#phoneCountry').html();
            var data = {
                after_style: 'send_auth_code',
                update: {
                    'mobile':'0086'+$scope.buyer.buyer_phone
                }
            };
            $http({
                method: "post",
                url: "/flight/rest/authCode/",
                data: $.param(data),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function (res) {
                if (res.errno != 0) {
                    mAlert(res.error);
                } else{
                    $interval.cancel($scope.timed_task);
                    $scope.show_timeout_info=true;
                    $scope.show_send_button = false;
                    $scope.task_time = 60;
                    $scope.add_task_time();
                    $scope.timed_task = $interval($scope.add_task_time,1000);
                    $scope.$watch('task_time',function () {
                        if($scope.task_time == 0){
                            $interval.cancel($scope.timed_task);
                            $scope.show_send_button = true;
                            $scope.show_timeout_info = false;
                        }
                    })
                }
            });
        }
        $scope.add_task_time = function () {
            $scope.task_time-=1;
            $scope.timeout_info = $scope.task_time+'秒后重试';
        }
        //临时下掉验证码


        $scope.isInResultList = function (id_no) {
            if ($scope.psgerResultList) {
                for (var i = 0; i < $scope.psgerResultList.length; i++) {
                    if ($scope.psgerResultList[i]['id_no'] == id_no) {
                        return true;
                    }
                }
            }
            return false;
        };

        $scope.initInsureView = function(){
            $('#insur_jiulvxing').show();
            $scope.containDelayInsure = false;
            $scope.containAccidentInsure = false;
        }
        $scope.initInsureView();

        $scope.getPsgerList = function () {
            var data = {
                page: { mode: 'random_total', num: 50, no: 1 },
                filter: { uid: $scope.uid },
                filter_style: 'get_psger_list'
            };
            $.ajax({
                type: 'GET',
                url: '/flight/rest/passengers/',
                data: data,
                dataType: 'json',
                success: function (res) {
                    $scope.$apply(function () {
                        if (res.data && res.data.ex && res.errno == 0) {
                            $scope.psgerList = res.data.ex.list;
                            $scope.backUpPsgerList = res.data.ex.list;
                            $scope.showPsgerList = $scope.backUpPsgerList.length > 7 ? $scope.backUpPsgerList.slice(0, 7) : $scope.backUpPsgerList;
                            angular.forEach($scope.psgerList, function(psger){
                                psger.passenger_type = isChild(psger.birth, $scope.seat_result_go.dep_date) ? 2 : 1;
                                if(psger.identity_list && psger.identity_list.length > 0){
                                    psger.default_identity = psger.identity_list[0];
                                } else {
                                    psger.default_identity = {
                                        id_type: '1',
                                        id_no: '',
                                        validity_date: '0000-00-00'
                                    }
                                }

                            });
                            $scope.addEmptyPsger();
                        }
                    });
                }
            });
        };

        $scope.getBuyerList = function () {
            var data = {
                page: { mode: 'random_total', num: 50, no: 1 },
                filter: { uid: $scope.uid }
            };
            $.ajax({
                type: 'GET',
                url: '/flight/rest/contacts/',
                data: data,
                dataType: 'json',
                success: function (res) {
                    $scope.$apply(function () {
                        if (res.data && res.data.ex && res.errno == 0) {
                            $scope.buyerList = res.data.ex.list;
                            $scope.showBuyerList = $scope.buyerList.length > 7 ? $scope.buyerList.slice(0, 7)
                                : $scope.buyerList;
                            if ($scope.buyerList.length > 0) {
                                $scope.selectBuyer($scope.buyerList[0]);
                            }
                        }
                    });
                }
            });
        };

        $scope.searchStopFlight = function (flight_no, dep_date, type) {
            var data = {
                filter: { flight_no: flight_no, dep_date: dep_date }
            };
            $.ajax({
                type: 'GET',
                url: '/flight/rest/flightStop/',
                data: data,
                dataType: 'json',
                success: function (res) {
                    $scope.$apply(function () {
                        if (res.data && res.data.ex && res.data.ex.errno == 0) {
                            if (type == 'go') {
                                $scope.stop_infos_go = res.data.ex.stop_infos;
                            } else if (type == 'back') {
                                $scope.stop_infos_back = res.data.ex.stop_infos;
                            }
                        }
                    });
                }
            });
        };

        $scope.setAirlinePrice = function () {
            if ($scope.containAccidentInsure) {
                $scope.settle_price_go = ($scope.seat_info_go.settle_price_insurance && $scope.seat_info_go.settle_price_insurance > 0)
                    ? $scope.seat_info_go.settle_price_insurance : $scope.seat_info_go.settle_price;    //航意险影响价格
                if ($scope.type == "roundWay") {
                    $scope.settle_price_back = ($scope.seat_info_back.settle_price_insurance && $scope.seat_info_back.settle_price_insurance > 0)
                        ? $scope.seat_info_back.settle_price_insurance : $scope.seat_info_back.settle_price;    //航意险影响价格
                }
            } else {
                $scope.settle_price_go = $scope.seat_info_go.settle_price; //航意险影响价格
                if ($scope.type == "roundWay") {
                    $scope.settle_price_back = $scope.seat_info_back.settle_price;    //航意险影响价格
                }
            }
        };

        $scope.calCulateChildNums = function () {
            $scope.psgerChildNums = 0;
            angular.forEach($scope.psgerResultList, function (one) {
                if (isChild(one.birth, $scope.seat_result_go.dep_date) || one.passenger_type == '2') {
                    $scope.psgerChildNums++;
                }
            });
        };

        $scope.calculateInsurePrice = function () {
            var insurePrice = 0;

            if ($scope.containDelayInsure && $scope.containAccidentInsure) {
                insurePrice = 60;
            }
            else if ($scope.containDelayInsure && !$scope.containAccidentInsure) {
                insurePrice = 30;
            }
            else if (!$scope.containDelayInsure && $scope.containAccidentInsure) {
                insurePrice = 30;
            }
            else {
                insurePrice = 0;
            }

            return insurePrice;
        };

        $scope.calculatePrice = function () {
            $scope.single_adult_settle_price_go = parseInt($scope.settle_price_go) + parseInt($scope.seat_result_go.airport_tax_audlet) + parseInt($scope.seat_result_go.fuel_tax_audlet);
            $scope.single_child_settle_price_go = parseInt($scope.seat_info_go.settle_price_child) + parseInt($scope.seat_result_go.airport_tax_child) + parseInt($scope.seat_result_go.fuel_tax_child);

            $scope.single_insure_price_go = $scope.calculateInsurePrice();
            $scope.invoice_price = $scope.needInvoice ? $scope.invoicePrice : 0;

            $scope.order_total_price = $scope.single_adult_settle_price_go * ($scope.psgerResultList.length - $scope.psgerChildNums)
                + $scope.single_child_settle_price_go * $scope.psgerChildNums
                + $scope.single_insure_price_go * $scope.psgerResultList.length + $scope.invoice_price;

            if ($scope.type == "roundWay") {
                $scope.single_adult_settle_price_back = parseInt($scope.settle_price_back) + parseInt($scope.seat_result_back.airport_tax_audlet) + parseInt($scope.seat_result_back.fuel_tax_audlet);
                $scope.single_child_settle_price_back = parseInt($scope.seat_info_back.settle_price_child) + parseInt($scope.seat_result_back.airport_tax_child) + parseInt($scope.seat_result_back.fuel_tax_child);

                $scope.single_insure_price_back = $scope.calculateInsurePrice();
                $scope.order_total_price += $scope.single_adult_settle_price_back * ($scope.psgerResultList.length - $scope.psgerChildNums)
                    + $scope.single_child_settle_price_back * $scope.psgerChildNums
                    + $scope.single_insure_price_back * $scope.psgerResultList.length;
            }
        };

        // 统一计算优惠券最终优惠的价格
        $scope.getCouponPrice = function () {       
          if(!$scope.selectedCoupon.use) return 0;
          // 以下逻辑从getPaymentPrice 拿过来 不做修改
          if ($scope.isDiscountCoupon($scope.selectedCoupon)) {
              var discount = $scope.order_total_price * $scope.selectedCoupon.discount_value/10;

              $fPrice = discount <= $scope.selectedCoupon.discount_max_value
                  ? discount
                  : $scope.selectedCoupon.discount_max_value;
              return Math.floor($fPrice * 100) / 100; //折扣优惠券保留2位小数
          } else {
              return $scope.selectedCoupon.discount_value ? $scope.selectedCoupon.discount_value : 0;
          }
        };

        $scope.getPaymentPrice = function () {
            $scope.calCulateChildNums();
            $scope.calculatePrice();

            // if ($scope.isDiscountCoupon($scope.selectedCoupon)) {
            //     var discount = $scope.order_total_price * $scope.selectedCoupon.discount_value/10;

            //     $fPrice = discount <= $scope.selectedCoupon.discount_max_value
            //         ? $scope.order_total_price - discount
            //         : $scope.order_total_price - $scope.selectedCoupon.discount_max_value;
            //     return Math.floor($fPrice * 100) / 100; //折扣优惠券保留2位小数
            // } else {
            //     return $scope.order_total_price - ($scope.selectedCoupon.discount_value ? $scope.selectedCoupon.discount_value : 0);
            // }
            return $scope.order_total_price - $scope.getCouponPrice();
        };

        $scope.getAirlineInfo = function () {
            var seat_infos_go = $scope.comeFrom == 'bq' ? $scope.seat_result_go.bq_seat_infos_show : $scope.seat_result_go.price_seat_infos;

            if ($scope.type == 'roundWay' && $scope.seat_go_selected != '') {
                $scope.seat_result_back = angular.fromJson(localStorage.getItem('seat_infos_back'));
                var seat_infos_back = $scope.comeFrom == 'bq' ? $scope.seat_result_back.bq_seat_infos_show : $scope.seat_result_back.price_seat_infos;
                angular.forEach(seat_infos_go, function (one) {
                    if (one.seat_xid == $scope.seat_go_selected) {
                        $scope.seat_info_go = one;
                    }
                });
                angular.forEach(seat_infos_back, function (one) {
                    if (one.seat_xid == $scope.selected) {
                        $scope.seat_info_back = one;
                    }
                });
            } else {
                angular.forEach(seat_infos_go, function (one) {
                    if (one.seat_xid == $scope.selected) {
                        $scope.seat_info_go = one;
                    }
                });
            }
            $scope.supportChildren = $scope.seat_info_go.settle_price_child != 0;

            var weekData = ['日', '一', '二', '三', '四', '五', '六'];
            var goDepartDate = new Date($scope.seat_result_go.dep_date);
            $scope.goDepartDay = (goDepartDate.getMonth() + 1) + '月' + goDepartDate.getDate() + '日';
            $scope.goDepartWeek = '周' + weekData[goDepartDate.getDay()];
            $scope.goDepTime = $scope.seat_result_go.dep_date + 'T' + $scope.seat_result_go.dep_time + ':00';
            $scope.goArrTime = $scope.seat_result_go.arr_date + 'T' + $scope.seat_result_go.arr_time + ':00';
            var goDepTime = new Date($scope.goDepTime);
            var goArrTime = new Date($scope.goArrTime);
            var goTakingDays = getTakingDays(new Date($scope.seat_result_go.dep_date + ' ' + $scope.seat_result_go.dep_time), new Date($scope.seat_result_go.arr_date + ' ' + $scope.seat_result_go.arr_time));
            if ($scope.seat_result_go.stop_num > 0) {
                $scope.isStopGoFlight = true;
                if ($scope.seat_result_go && $scope.seat_result_go.flight_no && $scope.seat_result_go.dep_date) {
                    $scope.searchStopFlight($scope.seat_result_go.flight_no, $scope.seat_result_go.dep_date, 'go');
                }
            }
            $scope.go_plus_day = $scope.isStopGoFlight ? '经停' : (goTakingDays > 0 ? ('+' + goTakingDays + '天') : '');
            $scope.goTakingDays = (goTakingDays > 0 ? ('+' + goTakingDays + '天') : '');
            $scope.go_taking_time = getTakingTime(goDepTime, goArrTime);

            $scope.seat_result_go.org_airport_full_name = $scope.seat_result_go.org_airport_name + $scope.seat_result_go.org_airport_quay;
            $scope.seat_result_go.dst_airport_full_name = $scope.seat_result_go.dst_airport_name + $scope.seat_result_go.dst_airport_quay;

            $scope.goAirline = $scope.seat_result_go.airline_name + $scope.seat_result_go.flight_no;
            $scope.goPlaneType = $scope.seat_result_go.plane_name;
            $scope.goAirlineInfo = $scope.goPlaneType;

            if ($scope.type == 'roundWay' && $scope.seat_go_selected != '') {
                var backDepartDate = new Date($scope.seat_result_back.dep_date);
                $scope.backDepartDay = (backDepartDate.getMonth() + 1) + '月' + backDepartDate.getDate() + '日';
                $scope.backDepartWeek = '周' + weekData[backDepartDate.getDay()];
                $scope.backDepTime = $scope.seat_result_back.dep_date + ' ' + $scope.seat_result_back.dep_time;
                $scope.backArrTime = $scope.seat_result_back.arr_date + ' ' + $scope.seat_result_back.arr_time;
                var backDepTime = new Date($scope.backDepTime);
                var backArrTime = new Date($scope.backArrTime);
                var backTakingDays = getTakingDays(new Date($scope.seat_result_back.dep_date + ' ' + $scope.seat_result_back.dep_time), new Date($scope.seat_result_back.arr_date + ' ' + $scope.seat_result_back.arr_time));
                if ($scope.seat_result_back.stop_num > 0) {
                    $scope.isStopBackFlight = true;
                    if ($scope.seat_result_back && $scope.seat_result_back.flight_no && $scope.seat_result_back.dep_date) {
                        $scope.searchStopFlight($scope.seat_result_back.flight_no, $scope.seat_result_back.dep_date, 'back');
                    }
                }
                $scope.back_plus_day = $scope.isStopBackFlight ? '经停' : (backTakingDays > 0 ? ('+' + backTakingDays + '天') : '');
                $scope.backTakingDays = (backTakingDays > 0 ? ('+' + backTakingDays + '天') : '');
                $scope.back_flight_time = $scope.backDepartDay + ' ' + $scope.backDepartWeek + ' 飞行时间:' + getTakingTime(backDepTime, backArrTime);
                $scope.back_taking_time = getTakingTime(backDepTime, backArrTime);

                $scope.seat_result_back.org_airport_full_name = $scope.seat_result_back.org_airport_name + $scope.seat_result_back.org_airport_quay;
                $scope.seat_result_back.dst_airport_full_name = $scope.seat_result_back.dst_airport_name + $scope.seat_result_back.dst_airport_quay;

                $scope.backAirline = $scope.seat_result_back.airline_name + $scope.seat_result_back.flight_no;
                $scope.backPlaneType = $scope.seat_result_back.plane_name;
                $scope.backAirlineInfo = $scope.backPlaneType;
            }
            $scope.setAirlinePrice();
        };

        // $scope.checkCouponList = function () {
        //     angular.forEach($scope.couponList, function (couponInfo) {
        //         if (couponInfo.id == $scope.selectedCoupon.id) {
        //             couponInfo.showCheckOn = true;
        //         }
        //     })
        // };

        $scope.getCouponList = function () {
            var data = {filter:{used_type:'inland'}};
            $.ajax({
                type: 'GET',
                url: '/flight/rest/coupons/',
                data: data,
                dataType: 'json',
                success: function (res) {
                    if(res.errno === 0){
                        $scope.$apply(function(){
                            $scope.couponList = res.data.list;
                            if (!$scope.couponList || $scope.couponList.length == 0) {
                                $scope.showEmptyCouponView = true;
                            }
                            //$scope.checkCouponList();
                        });
                    }
                }
            });
        };

        $scope.getShowCouponType = function (coupon) {
            if(!coupon) coupon = $scope.selectedCoupon;
            return coupon.discount_type > 0 ? 3 : (coupon.cond_price > 0 ? 2 : 1);
        };

        $scope.getScopeName = function (scopeName) {
            return scopeName == '机票频道' ? '机票频道(每单立减)' : scopeName;
        };

        $scope.verificationCode = function () {
            var data = { after_style: 'default', update: {action: 'add', code: $scope.couponCode} };
            $http({
                method: "post",
                url: "/flight/rest/coupons/",
                data: $.param({jsondata: JSON.stringify(data)}),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function (res) {
                if (res.data.after.error_no == 0) {
                    $scope.getCouponList();
                } else {
                    mAlert(res.data.after.error_msg);
                }
            });
        };

        $scope.setDefaultCoupon = function () {
            if ($scope.psgerResultList.length > 0 && !$scope.inner.busi_inner_desc) {

                if(!$scope.psgerResultList[0].passenger_name) return ;

                if ($scope.couponDefault && $scope.couponDefault.usable) {
                    $scope.selectedCoupon = $scope.couponDefault;
                    $scope.selectedCoupon.use = true;
                }
            }
        };

        

        $scope.clearSelectedCoupon = function () {
            $scope.selectedCoupon.use = false;
        };

        $scope.isDiscountCoupon = function(coupon) {
            return coupon.discount_type == 1;
        };

        // 下单绑定手机号判断
        $scope.bindPhoneNumberJudge = function () {
          if(!window.Env.MOBILE_BINDED) {
            mAlert(
              '应《网络安全法》要求，您需要绑定手机号。',
              '',
              function () {
                location.href = window.Env.P_HTTP+'/setting/security/mobile/';
              },
              1,
              true
            );
          }
        };

        $scope.init = function () {
            // 2019-01-07 增加下单绑定手机号
            $scope.bindPhoneNumberJudge();
            $scope.getPsgerList();
            $scope.getBuyerList();
            $scope.getAirlineInfo();
            $scope.getCouponList();
        };
        $scope.init();

        $scope.morePsger = function () {
            var contact = $("#psger_list");
            if (contact.hasClass("extend")) {
                $scope.showPsgerList = $scope.psgerList.length > 7 ? $scope.psgerList.slice(0, 7) : $scope.psgerList;
                contact.removeClass("extend");
            } else {
                $scope.showPsgerList = $scope.psgerList;
                contact.addClass("extend");
            }
        };

        $scope.$watch('psgerResultList', function (nv) {
            for (var i = 0; i < $scope.psgerResultList.length; i++) {
                $scope.findElement('psger-name-item-' + $scope.psgerResultList[i].id);
                $scope.checkPsger($scope.psgerResultList[i]);
            }
        }, true);
        $scope.$watch('buyer', function (nv) {
            $scope.findElement('buyer_name');
            $scope.findElement('buyer_phone');
        }, true);
        $scope.$watch('invoice_info', function (nv) {
            $scope.findElement('invoice_title');
            $scope.findElement('invoice_tax_number');
            $scope.findElement('invoice_name');
            $scope.findElement('invoice_addr');
        }, true);
        $scope.findElement = function (element_id) {
            $timeout(function () {
                if (document.getElementById(element_id)) {
                    $scope.addSecFocu();
                } else {
                    $scope.findElement();
                }
            }, 100);
        };


        $scope.addSecFocu = function(element_id){
            $('.form-sec').each(function (index) {
                var $this = $(this).on('focusin',function(){
                    $(this).addClass('form-sec-active');
                }).on('focusout change',function(){
                    $(this).removeClass('form-sec-active');
                }).on('change focusout', function() {
                    // $this.find(‘input,select,textarea').val().length>0
                    if($this.find('input,select,textarea').val()){
                        $(this).addClass('form-sec-focus');
                    }else{
                        $(this).removeClass('form-sec-focus');
                    }
                });

                // $('.form-sec input').eq(index).val().length > 0
                if ($this.find('input').val()) {
                    $(this).addClass('form-sec-focus');
                    $(this).removeClass('form-sec-active');
                } else {
                    $(this).removeClass('form-sec-focus');
                    $(this).removeClass('form-sec-active');
                }
                $('.form-sec label').click(function () {
                    $(this).next().focus();
                });
            });
        }

        $scope.getDisplayName = function (one) {
            return one.passenger_name ? one.passenger_name : one.last_name + '/' + one.first_name;
        };

        $scope.addPsgerView = function(){
            $scope.addEmptyPsger();
        }

        $scope.selectPsger = function (one) {
            mfwPageEvent('flight', 'list_passenger', {
                'name': '选择乘机人'
            });
            $scope.findElement('psger-name-item-' + one.id);
            if(!one.default_identity){
                one.default_identity = {
                    id_type: '1',
                    id_no: '',
                    validity_date: '0000-00-00'
                }
            }
            var selectedPsgerOne = $('[data-psger-id=' + one.id + ']');
            if (selectedPsgerOne.hasClass('on')) {
                selectedPsgerOne.removeClass('on');
                for (var i = 0; i < $scope.psgerResultList.length; i++) {
                    if ($scope.psgerResultList[i].id == one.id) {
                        $scope.psgerResultList.splice(i, 1);
                        break;
                    }
                }
                if($scope.psgerResultList.length == 0){
                    $scope.addEmptyPsger();
                }
            } else {
                if(!$scope.supportChildren && one.passenger_type == '2'){
                    mAlert('该航班暂时不支持儿童票');
                    return;
                }
                selectedPsgerOne.addClass('on');
                var addFlag = false;
                for (var i = 0; i < $scope.psgerResultList.length; i++) {
                    if($scope.psgerResultList[i].flag == 'new' ){
                        if($scope.psgerResultList[i].passenger_name == '' 
                            && $scope.psgerResultList[i].default_identity.id_no == ''
                            && $scope.psgerResultList[i].default_identity.id_type == '1'){
                            $scope.psgerResultList[i] = one;
                            $scope.psgerResultList[i].passenger_name = $scope.getDisplayName(one);
                            addFlag = true;
                            break;
                        }
                    }
                }
                if(!addFlag) $scope.psgerResultList.push(one);

                if(!$scope.selectedCoupon.coupon_code){ $scope.setDefaultCoupon(); }
                
            }

            $scope.calCulateChildNums();
            $scope.calculatePrice();
        };


        $scope.deletePsger = function (one) {
            for (var i = 0; i < $scope.psgerResultList.length; i++) {
                if ($scope.psgerResultList[i].id == one.id) {
                    if (!isChild(one.birth, $scope.seat_result_go.dep_date) && one.passenger_type != '2') {
                        $scope.calCulateChildNums();
                        $scope.calculatePrice();
                        if ($scope.psgerChildNums > 0 && $scope.psgerResultList.length - $scope.psgerChildNums - 1 < 1) {
                            mAlert("儿童必须有成年人陪护喔");
                            return;
                        }
                    }
                    $scope.psgerResultList.splice(i, 1);
                    $('[data-psger-id=' + one.id + ']').removeClass('on');
                }
            }
            if ($scope.psgerResultList && $scope.psgerResultList.length == 0) {
                if ($scope.selectedCoupon.use) {
                    $scope.clearSelectedCoupon();
                }
                $scope.addEmptyPsger();

            }
            $scope.calCulateChildNums();
            $scope.calculatePrice();
        };

        $scope.addEmptyPsger = function () {
            var id = $scope.tmpid++;
            var psger = {
                id: id,
                uid: "",
                birth: "",
                id_type_name: "身份证",
                passenger_name: "",
                passenger_type: "1",
                sex: "0",
                identity_list: [],
                default_identity: {
                    id_type: "1",
                    id_no: '',
                    validity_date: '0000-00-00'
                },
                flag: "new" //new表示新增一个空乘机人
            };
            $scope.psgerResultList.push(psger);
            $scope.setDefaultCoupon();
        };

        $scope.moreBuyer = function () {
            var buyer = $("#buyer_list");
            if (buyer.hasClass("extend")) {
                $scope.showBuyerList = $scope.buyerList.length > 7 ? $scope.buyerList.slice(0, 7) : $scope.buyerList;
                buyer.removeClass("extend");
            } else {
                $scope.showBuyerList = $scope.buyerList;
                buyer.addClass("extend");
            }
        };

        $scope.selectBuyer = function (one) {
            mfwPageEvent('flight', 'list_contacts', {
                'name': '选择联系人'
            });
            var selectedBuyerOne = $('[data-buyer-id=' + one.id + ']');
            if (selectedBuyerOne.hasClass('on')) {
                selectedBuyerOne.removeClass('on');
                $scope.buyer = {
                    buyer_id: "",
                    buyer_name: "",
                    buyer_phone: "",
                    buyer_email: ""
                };
            } else {
                $('[data-buyer-id]').removeClass('on');
                selectedBuyerOne.addClass('on');
                $scope.buyer.buyer_id = one.id;
                $scope.buyer.buyer_name = one.name;
                $scope.buyer.buyer_phone = one.phone;
                $scope.buyer.buyer_email = one.email;
            }
        };

        $scope.selectIdTypeView = function(one){
            $('#psger-id-type-' + one.id).show();
        }

        $scope.selectIdType = function(one, idItem){
            var isInList = false;
            var templist = [];
            angular.copy(one.identity_list, templist);
            angular.forEach(one.identity_list, function(identity){
                if(idItem.id_type == identity.id_type){
                    one.default_identity.id = identity.id;
                    one.default_identity.id_no = identity.id_no;
                    one.default_identity.id_type = identity.id_type;
                    one.default_identity.validity_date = identity.validity_date;
                    isInList = true;
                }
            });
            angular.copy(templist,one.identity_list);
            if(!isInList){
                one.default_identity.flag = 'new';
                one.default_identity.id = 0;
                one.default_identity.id_no = '';
                one.default_identity.id_type = idItem.id_type;
                one.default_identity.validity_date = '0000-00-00';
            }
            if(one.default_identity.id_type != '1'){
                one.sex = '0';
                $('#psg-id-birth-' + one.id).val('');
            }else{
                $('#psg-id-birth-' + one.id).val('');
            }
            one.passenger_name = '';
        }

        $scope.selectPsgerType = function(one, psgerType){
            one.passenger_type = psgerType;
            $scope.checkPsger(one);
            $scope.calCulateChildNums();
            $scope.calculatePrice();
        }

        $scope.selectPsgerSex = function(one, psgerSex){
            one.sex = psgerSex;
        }

        $scope.isPassengerName = function (name) {
            var Regx = /^([a-z]+\/[a-z]+|[\u4e00-\u9fa5·]+)$/i;
            return Regx.test(name) !== false;
        };

        $scope.filterErrorName = function (name) {
            return name.replace(/[^\a-\z\A-\Z\u4E00-\u9FA5\/]/g,'');
        };

        $scope.filterTaxNumber = function () {
            $scope.invoice_info.tax_number = $scope.invoice_info.tax_number.replace(/[^a-zA-Z0-9]/g,'');
        };

        $scope.checkPsger = function (one, flag) {
            var ret = true;
            if (one.passenger_name && !$scope.isPassengerName(one.passenger_name)) {
                $timeout(function () {
                    $scope.showIdNoError(one, 'psger-name-item-');
                }, 200);
                ret = false;
            }
            if(one.birth){
                $scope.calCulateChildNums();
                $scope.calculatePrice();
            }
            var birthDay;
            if (one.default_identity.id_type == '1') {
                $('#psg-id-birth-view-' + one.id).hide();
                if (one.default_identity.id_no) {
                    birthDay = getBirthdatByIdNo(one.default_identity.id_no);
                    one.passenger_type = isChild(birthDay, $scope.seat_result_go.dep_date) ? '2' : '1';
                    if (!IdentityCodeValid(one.default_identity.id_no)) {
                        $timeout(function () {
                            $scope.showIdNoError(one, 'psger-id-no-');
                        }, 200);
                        ret = false;
                    }
                    if (birthDay && isBaby(birthDay, $scope.seat_result_go.dep_date)) {
                        mAlert("婴儿乘机请联系客服电话购买");
                        $timeout(function () {
                            $scope.showIdNoError(one, 'psger-id-no-');
                        }, 200);
                        ret = false;
                    }
                }
            } else {
                $timeout(function () {
                    $('#psg-id-birth-view-' + one.id).show();
                    $('#psg-id-birth-' + one.id).datetimepicker({
                        // datepicker:false,
                        timepicker: false,
                        lang: 'zh',
                        format: 'Y-m-d',
                        formatDate: 'Y-m-d',
                        todayButton: false,
                        scrollMonth: false,
                        scrollInput: false,
                        showApplyButton: false,
                        initTime: false,
                        defaultSelect: false,
                        theme: 'mfw',
                        yearStart: 1900,
                        yearEnd: 2050
                    });

                }, 200);
                birthDay = one.birth;
                if(!birthDay || birthDay == '0000-00-00'){
                    ret = false;
                    $timeout(function () {
                        $scope.showIdNoError(one, 'psg-id-birth-label-');
                    }, 400);
                }else{
                    $('#psg-id-birth-' + one.id).val(birthDay);
                    $scope.findElement('psg-id-birth-' + one.id);
                    var passengerType = isChild(birthDay, $scope.seat_result_go.dep_date) ? '2' : '1';
                    if (one.passenger_type != passengerType) {
                        $timeout(function () {
                            $scope.showIdNoError(one, 'psger-type-item-');
                        }, 200);
                        ret = false;
                    }
                    if(isErrorBirth(birthDay, formatDateTime(new Date()))){
                        $timeout(function () {
                            $scope.showIdNoError(one, 'psg-id-birth-label-');
                        }, 400);
                        ret = false;
                    }
                    if (birthDay && isBaby(birthDay, $scope.seat_result_go.dep_date)) {
                        mAlert("婴儿乘机请联系客服电话购买");
                        $timeout(function () {
                            $scope.showIdNoError(one, 'psg-id-birth-label-');
                        }, 200);
                        ret = false;
                    }
                }
            }
            if (!$scope.supportChildren && birthDay && isChild(birthDay, $scope.seat_result_go.dep_date)) {
                mAlert('该航班暂时不支持儿童票');
                ret = false;
            }
            if (flag) {
                if (!one.default_identity.id_no) {
                    $timeout(function () {
                        $scope.showIdNoError(one, 'psger-id-no-');
                    }, 500);
                    ret = false;
                }
                if (!one.passenger_name || !$scope.isPassengerName(one.passenger_name)) {
                    $timeout(function () {
                        $scope.showIdNoError(one, 'psger-name-item-');
                    }, 500);
                    ret = false;
                }
                if (one.default_identity.id_type != '1' && !one.birth) {
                    $timeout(function () {
                        $scope.showIdNoError(one, 'psg-id-birth-label-');
                    }, 500);
                    ret = false;
                }
            }
            return ret;
        }

        $scope.showIdNoError = function(one , element_id){
            $('#' + element_id + one.id).addClass('form-sec-focus');
            $('#' + element_id + one.id).addClass('form-sec-active');
        }

        $scope.idNoMouseup = function(one){
            $scope.checkPsger(one);
        }

        $scope.nameMouseup = function(one){
            $scope.checkPsger(one);
        }

        $scope.showCalendar = function(one){
            $('#psg-id-birth-' + one.id).datetimepicker({
                // datepicker:false,
                timepicker: false,
                lang: 'zh',
                format: 'Y-m-d',
                formatDate: 'Y-m-d',
                todayButton: false,
                scrollMonth: false,
                scrollInput: false,
                showApplyButton: false,
                initTime: false,
                defaultSelect: false,
                theme: 'mfw',
                yearStart: 1900,
                yearEnd: 2050
            });
        }

        $scope.isPassengerName = function (name) {
            var Regx = /^([a-z]+\/[a-z]+|[\u4e00-\u9fa5·]+)$/i;
            return Regx.test(name) !== false;
        };

        $scope.isPhoneNo = function (phone_num) {
            return !(phone_num == null || phone_num == '' );
        };

        $scope.isCardNo = function (id_no) {
            var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            return reg.test(id_no) !== false;
        };

        $scope.getUserIdInfo = function (one) {
            var psgerType = '（成人）';
            if (isChild(one.birth, $scope.seat_result_go.dep_date)) {
                psgerType = '（儿童）';
            }
            return $scope.getIdNo(one) + psgerType;
        };

        $scope.getIdNo = function (one) {
            var result = '';
            if (one.default_identity.id_type == 1) {
                result = "身份证:" + one.default_identity.id_no;
            } else {
                result = $scope.getIdName(one.default_identity.id_type) + ":" + one.default_identity.id_no;
            }
            return result;
        };

        $scope.getIdName = function (id_type) {
            if ($scope.idTypes && $scope.idTypes.length > 0) {
                for (var i = 0; i < $scope.idTypes.length; i++) {
                    if (id_type == $scope.idTypes[i]['id_type']) {
                        return $scope.idTypes[i]['id_type_name'];
                    }
                }
            }
            return '身份证';
        };

        $scope.clickCouponDiv = function () {
            var couponPop = $(".coupon-pop");
            if (!couponPop.is(":visible")) {
                couponPop.show();
                if($scope.selectedCoupon.use){
                    $('[data-coupon-code=' + $scope.selectedCoupon.coupon_code + ']').addClass("on");
                }
            } else {
                couponPop.hide();
            }
        };

        $scope.useCoupon = function () {
            $(".coupon-pop").hide();
        };
        $scope.cancelUsingCoupon = function () {
            $scope.clearSelectedCoupon();
            $(".coupon-pop").hide();
            $('[data-coupon-code]').removeClass("on");
        };

        $scope.selectCoupon = function (one) {
            if ($scope.psgerResultList < 1) {
                mAlert("请先选择乘机人")
            } else {
                // if ($scope.containAccidentInsure == false && one.price != 20) {
                //     $("#coupon_view").hide();   //选择航意险才能用优惠券
                //     mAlert("购买航空意外险才有优惠券价格优惠");
                //     return;
                // }
                if ($scope.order_total_price < one.cond_price) {
                    mAlert("订单价格未达到优惠券满额条件");
                    return;
                } else if(!one.usable){
                    mAlert("优惠券类型不可使用");
                    return;
                } else {

                    angular.forEach($scope.couponList, function (couponInfo) {
                        var curCheck = $('[data-coupon-code=' + couponInfo.coupon_code + ']');
                        if (couponInfo.coupon_code == one.coupon_code) {
                            if(!curCheck.hasClass('on')){
                                curCheck.addClass('on');
                                $scope.selectedCoupon = one;
                                $scope.selectedCoupon.use = true;
                                $(".coupon-pop").hide();
                                return false;
                            }else{
                                $scope.clearSelectedCoupon();
                            }
                        }
                        curCheck.removeClass("on");
                    });
                }
            }
        };

        //点击航意险
        $scope.clickAccidentInsure = function () {
            var btn = $("#accidentInsureBtn");
            if (!btn.hasClass("on")) {
                $scope.containAccidentInsure = true;
                btn.addClass("on");
                if(!$scope.selectedCoupon.use){
                    $scope.setDefaultCoupon();
                }
            } else {
                // if (($scope.seat_info_go.required_goods_ids && $scope.seat_info_go.required_goods_ids.indexOf(17) >= 0)
                //     || ($scope.type == "roundWay" && $scope.seat_info_back.required_goods_ids && $scope.seat_info_back.required_goods_ids.indexOf(17) >= 0)) {
                //     mAlert("套餐优惠机票不可去掉航意险");
                //     return;
                // }
                btn.removeClass("on");
                $scope.containAccidentInsure = false;
                // if ($scope.selectedCoupon.discount_value != 20) {
                //     $("#coupon_view").hide();   //选择航意险才能用优惠券
                //     mAlert("购买航空意外险才有优惠券价格优惠");
                //     $scope.clearSelectedCoupon();
                // }
            }

            $scope.setAirlinePrice();
            $scope.calculatePrice();    //重新计算价格

            mfwPageEvent('flight', 'insure_accident_click', {
                'buyer_name': $scope.buyer.buyer_name
            });
        };
        //点击延误险或者组合险
        $scope.clickDelayInsure = function () {
            var btn = $("#delayInsureBtn");
            if (!btn.hasClass("on")) {
                $scope.containDelayInsure = true;
                btn.addClass("on");
            } else {
                // if (($scope.seat_info_go.required_goods_ids && $scope.seat_info_go.required_goods_ids.indexOf(11) >= 0)
                //     || ($scope.type == "roundWay" && $scope.seat_info_back.required_goods_ids && $scope.seat_info_back.required_goods_ids.indexOf(11) >= 0)) {
                //     mAlert("套餐优惠机票不可去掉延误险");
                //     return;
                // }
                btn.removeClass("on");
                $scope.containDelayInsure = false;
            }

            $scope.setAirlinePrice();
            $scope.calculatePrice();    //重新计算价格

            mfwPageEvent('flight', 'insure_delay_click', {
                'buyer_name': $scope.buyer.buyer_name
            });
        };


        $scope.showInvoice = function (type) {
            if ($("#invoice_info").is(":hidden")) {
                $.ajax({
                    type: 'GET',
                    url: '/flight/rest/invoice/',
                    data: {},
                    dataType: 'json',
                    success: function (res) {
                        if (res.data.ex != null && res.data.ex != '') {
                            $scope.$apply(function () {
                                $scope.invoice_info.name = res.data.ex.name;
                                $scope.invoice_info.title = res.data.ex.title;
                                $scope.invoice_info.tax_number = res.data.ex.tax_number;
                                $scope.invoice_info.addr = res.data.ex.addr;
                                $scope.invoice_info.invoice_type = $scope.seat_info_go.policy_info.invoice_type;
                                if (res.data.ex.inner) {
                                    $scope.inner.is_busi_inner = 1;
                                    $("#invoice_inner_note").show();
                                } else {
                                    $scope.inner.is_busi_inner = -1;
                                    $scope.inner.busi_inner_desc = '';
                                    $("#invoice_inner_note").hide();
                                }
                            });
                        }
                    }
                });
                if (type == 1) {
                    $("#invoice_type2").removeClass("on");
                    $("#invoice_type1").addClass("on");
                } else {
                    $("#invoice_type1").removeClass("on");
                    $("#invoice_type2").addClass("on");
                }
                $("#invoice_info").show();
                $scope.needInvoice = true;
            } else {
                $("#invoice_type1").removeClass("on");
                $("#invoice_type2").removeClass("on");
                $("#invoice_info").hide();
                $scope.needInvoice = false;
            }
        };

        //港澳通行证、台湾通行证转成其他（适应旅伴）
        $scope.getIdTypeForFlight = function(id_type){
            return (id_type == 7 || id_type == 8) ? 6 : id_type;
        }

        $scope.aGetFormatOrderPnrs = function () {
            var orderPnrs = [];
            angular.forEach($scope.psgerResultList, function (one) {
                var birth = (one.default_identity.id_type == 1) ? getBirthdatByIdNo(one.default_identity.id_no) : one.birth;
                var pnr = {
                    ota_id: $scope.otaId,
                    dep_date: $scope.seat_result_go.dep_date,
                    flight_no: $scope.seat_result_go.flight_no,
                    seat_code: $scope.seat_info_go.code,
                    package_name: $scope.seat_info_go.package_name,
                    passenger_name: $scope.filterErrorName($scope.getDisplayName(one)),
                    passenger_type: isChild(birth, $scope.seat_result_go.dep_date) ? 2 : 1,
                    id_type: $scope.getIdTypeForFlight(one.default_identity.id_type),
                    id_no: one.default_identity.id_no,
                    birth: (one.birth != "0000-00-00" ? one.birth : ''),
                    sex: one.sex != '1' ? 'F' : 'M',
                    policy_id: $scope.seat_info_go.policy_info ? $scope.seat_info_go.policy_info.id : '',
                    fareitem_id: $scope.seat_info_go.fareitem_id,
                    route_type: 0,  //接口定义的0为纯单程或往返的去程，1为往返的回程
                    goods: [],
                    org_airport_code: $scope.seat_result_go.org_airport,
                    dst_airport_code: $scope.seat_result_go.dst_airport
                };
                if ($scope.containDelayInsure) {
                    var delayInsure = {id: 37,nums: 1};
                    pnr["goods"].push(delayInsure);
                }
                if ($scope.containAccidentInsure) {
                    var accidentInsure = {id: 38,nums: 1};
                    pnr["goods"].push(accidentInsure);
                }
                orderPnrs.push(pnr);
                if ($scope.type == "roundWay") {
                    var pnrBack = {
                        ota_id: $scope.otaId,
                        dep_date: $scope.seat_result_back.dep_date,
                        flight_no: $scope.seat_result_back.flight_no,
                        seat_code: $scope.seat_info_back.code,
                        package_name: $scope.seat_info_back.package_name,
                        passenger_name: $scope.filterErrorName($scope.getDisplayName(one)),
                        passenger_type: isChild(birth, $scope.seat_result_back.dep_date) ? 2 : 1,
                        id_type: $scope.getIdTypeForFlight(one.default_identity.id_type),
                        id_no: one.default_identity.id_no,
                        birth: (one.birth != "0000-00-00" ? one.birth : ''),
                        sex: one.sex != '1' ? 'F' : 'M',
                        policy_id: $scope.seat_info_back.policy_info.id,
                        fareitem_id: $scope.seat_info_back.fareitem_id,
                        route_type: 1,
                        goods: [],
                        org_airport_code: $scope.seat_result_back.org_airport,
                        dst_airport_code: $scope.seat_result_back.dst_airport
                    };
                    if ($scope.containDelayInsure) {
                        pnrBack["goods"].push(delayInsure);
                    }
                    if ($scope.containAccidentInsure) {
                        pnrBack["goods"].push(accidentInsure);
                    }
                    orderPnrs.push(pnrBack);
                }
            });
            return orderPnrs;
        };

        $scope.aGetSelectedFlights = function () {
            var flights = [];
            flights[0] = [];
            var flight_go = $scope.seat_result_go;
            delete $scope.seat_result_go.bq_seat_infos_show;
            delete $scope.seat_result_go.bq_seat_infos_temp;
            delete $scope.seat_result_go.bq_seat_infos;
            delete $scope.seat_result_go.price_seat_infos;
            delete flight_go.seat_infos;
            flight_go.seat = $scope.seat_info_go;
            // IATA信息
            function iata(obj, key) {
                (obj.seat.provision_info && obj.seat[key]) && (obj.seat.provision_info[key] = obj.seat[key]);
            }
            iata(flight_go, 'supplierName');
            iata(flight_go, 'supplierIATANumber');
            // IATA信息
            flights[0].push(flight_go);
            if ($scope.type == "roundWay") {
                flights[1] = [];
                var flight_back = $scope.seat_result_back;
                delete $scope.seat_result_back.bq_seat_infos_show;
                delete $scope.seat_result_back.bq_seat_infos_temp;
                delete $scope.seat_result_back.bq_seat_infos;
                delete $scope.seat_result_back.price_seat_infos;
                delete flight_back.seat_infos;
                flight_back.seat = $scope.seat_info_back;
                iata(flight_back, 'supplierName');
                iata(flight_back, 'supplierIATANumber');
                flights[1].push(flight_back);
            }
            return flights;
        }

        $scope.preCheckOrderInfo = function () {
            var psgerInfoRight = true;
            angular.forEach($scope.psgerResultList, function (one) {
                psgerInfoRight = $scope.checkPsger(one, true);
                if (!psgerInfoRight) {
                    return false;
                }
                $scope.addOnePsger(one);
            });
            if (!psgerInfoRight) {
                mAlert("请确认乘机人信息");
                return false;
            }
            if ($scope.psgerResultList.length > 9) {
                mAlert("单次订票人数不能超过9个，请分开下单");
                return false;
            }

            if ($scope.buyer.buyer_phone == null || $scope.buyer.buyer_phone == undefined || $scope.buyer.buyer_phone == ''
                || $scope.buyer.buyer_name == null || $scope.buyer.buyer_name == undefined || $scope.buyer.buyer_name == '') {
                mAlert("请确认联系人信息");
                return false;
            }
            if (!$scope.isPhoneNo($scope.buyer.buyer_phone)) {
                mAlert("请输入正确的手机号码");
                return false;
            }

            if ($scope.needInvoice) {
                if ( !Boolean($scope.invoice_info.name) || !Boolean($scope.invoice_info.addr) ) {
                    mAlert("请确认报销凭证信息");
                    return false;
                }
                if ( !Boolean($scope.invoice_info.title) || !Boolean($scope.invoice_info.tax_number) ) {
                    mAlert("请填写报销凭证发票抬头和税号");
                    return false;
                }
            }
            return true;
        };

        $scope.addOnePsger = function (one) {
            if (one.flag != 'new') {
                $scope.updatePsgerFromServer(one);
            } else {
                $scope.addPsgerToServer(one)
                mfwPageEvent('flight', 'list_passenger', {
                    'name': '新增乘机人'
                });
            }
        };

        $scope.updatePsgerFromServer = function (one) {
            var isInList = false;
            angular.forEach(one.identity_list, function(identity){
                if(one.default_identity.id_type == identity.id_type){
                    isInList = true;
                }
            });
            if(!isInList && one.default_identity.id_no){
                one.identity_list.push(one.default_identity);
            }
            var data = {
                after_style: 'update',
                update: one
            };
            $http({
                method: "post",
                url: "/flight/rest/passengers/",
                data: $.param(data),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function (res) {
            });
        };

        $scope.addPsgerToServer = function (one) {
            var birthDay = '';
            if(one.default_identity.id_type == '1'){
                birthDay = getBirthdatByIdNo(one.default_identity.id_no);
            }else{
                birthDay = $('#psg-id-birth-' + one.id).val();
                if(!birthDay){
                    mAlert("请输入出生日期");
                    return;
                }
            }
            if (isBaby(birthDay, $scope.seat_result_go.dep_date)) {
                mAlert("婴儿乘机请联系客服电话购买");
                return;
            }
            one.birth = birthDay;
            one.identity_list[0] = one.default_identity;
            var data = {
                after_style: 'add',
                update: one
            };
            $http({
                method: "post",
                url: "/flight/rest/passengers/",
                data: $.param(data),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function (res) {
                if (res.errno == 0) {
                    if (res.data.key == -2) {
                    } else if (res.data.key == -3) {
                        mAlert("已超过乘机人数量限制");
                        return;
                    } else if (res.data.key == 0) {
                        mAlert("新增乘机人失败");
                        return;
                    }
                }
            });
        };

        $scope.isRightName = function (name) {
            if (!name) {
                return false;
            }
            return !(name.length < 2 || !isNaN(name));
        };

        $scope.addBuyerToServer = function (buyer_id, name, phoneNum, email, needShowBuyerList) {
            if (!$scope.isRightName(name)) {
                return;
            } else if (!phoneNum) {
                return;
            } else if (!$scope.isPhoneNo(phoneNum)) {
                return;
            } else {
                mfwPageEvent('flight', 'list_contacts', {
                    'name': '新增联系人'
                });
                var data = {
                    after_style: 'default',
                    update: {
                        action: 'add',
                        uid: $scope.uid,
                        id: buyer_id,
                        name: name,
                        phone: phoneNum,
                        email: email,
                        phoneCountry:'86'
                    }
                };
                $http({
                    method: "post",
                    url: "/flight/rest/contacts/",
                    data: $.param(data),
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                }).success(function (res) {
                    if (res.errno == 0) {
                        if (res.data.key == 0) {
                            if (needShowBuyerList) {
                                mAlert("新增联系人失败，请检查网络");
                            }
                            return;
                        } else if (res.data.key == -2) {
                            if (needShowBuyerList) {
                                mAlert("联系人已存在");
                            }
                            return;
                        } else if (res.data.key == -3) {
                            if (needShowBuyerList) {
                                mAlert("已超过联系人数量限制");
                            }
                            return;
                        } else if (res.data.key > 0) {
                            if (needShowBuyerList) {
                                $scope.hideBuyerBtn();
                                $scope.getBuyerList();
                                history.back();
                            }
                        }
                    }
                });
            }
        };

        $scope.submitOrder = function (deleteRepeatOrder) {
            if (!$scope.preCheckOrderInfo()) {
                return;
            }
            //临时下掉验证码
            var data = {
                after_style: 'validate_code',
                update: {
                    mobile: '0086'+$scope.buyer.buyer_phone,
                    short_mobile:$scope.buyer.buyer_phone,
                    phone_country:'86',
                    auth_code:$scope.buyer.auth_code,
                }
            }
            $http({
                method: "post",
                url: "/flight/rest/authCode/",
                data: $.param({jsondata: JSON.stringify(data)}),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function (res) {
                mfwPageEvent('flight', 'submit_auth_code', {    //提交验证码简单参数统计
                    'short_mobile':$scope.buyer.buyer_phone,
                    'phone_country':'86',
                    'auth_code': $scope.buyer.auth_code,
                    'errno':res.errno
                });
                if(res.errno != 0){
                    mAlert("验证码错误");
                    return;
                }else{
            //临时下掉验证码
                    $("#submitOrderLoading").show();    //阻塞用户操作，提高用户等待体验
                    $scope.addBuyerToServer($scope.buyer.buyer_id, $scope.buyer.buyer_name,
                        $scope.buyer.buyer_phone, $scope.buyer.buyer_email, false);
                    mfwPageEvent('flight', 'submit_order', {    //简单参数统计
                        'buyer_name': $scope.buyer.buyer_name,
                        'origin_price': $scope.order_total_price,
                        'payment_price': $scope.getPaymentPrice()
                    });
                    var invoiceFee = $scope.otaId == 101 ? [{id: 20, nums: 1}] : [{id: 31, nums: 1}];
                    var data = {
                        after_style: 'create_order',
                        update: {
                            delete_repeat_order:deleteRepeatOrder,
                            buyer: $scope.buyer.buyer_name,
                            mobile: '0086'+$scope.buyer.buyer_phone,
                            short_mobile: $scope.buyer.buyer_phone,
                            phone_country:'86',
                            auth_code:$scope.buyer.auth_code,
                            email: $scope.buyer.buyer_email,
                            price: $scope.order_total_price,
                            channel: 'pc',
                            coupon_code: $scope.selectedCoupon.use ? $scope.selectedCoupon.coupon_code : '',
                            ota_id: $scope.otaId,
                            invoice_info: ($scope.needInvoice ? $scope.invoice_info : []),
                            pnrs: $scope.aGetFormatOrderPnrs(),
                            flights: $scope.aGetSelectedFlights(),
                            goods: $scope.needInvoice ? invoiceFee : [],
                            is_busi_inner: -1,
                            busi_inner_desc: '',
                            dep_date: $scope.seat_result_go.dep_date
                        }
                    };
                    $http({
                        method: "post",
                        url: "/flight/rest/order/",
                        data: $.param({jsondata: JSON.stringify(data)}),
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                    }).success(function (res) {
                        if (res.errno == 0 && res.data.after.errno == 0) {
                            $("#submitOrderLoading").hide();
                            window.location.href = $scope.pay_base_url + res.data.after.mfw_order_id;
                        } else {
                            $("#submitOrderLoading").hide();
                            if(res.data.after.errno == 40){
                                mAlert(res.data.after.errmsg);
                            }else if(res.data.after.errno == 1403){
                              mAlert(
                                res.data.after.errmsg || '应《网络安全法》要求，您需要绑定手机号。',
                                '',
                                function () {
                                  location.href = window.Env.P_HTTP+'/setting/security/mobile/';
                                },
                                1,
                                true
                              );
                            }else{
                                mConfirm(res.data.after.errmsg, function (ok) {
                                    if(res.data.after.errno == 50){
                                        $scope.submitOrder(true);
                                    }else{
                                        $scope.bGoBackList = true;
                                        localStorage.setItem('seat_go_selected', '');
                                        var baseUrl = "/flight/list";
                                        var params = "?departCity=" + $scope.departCity + "&departCode=" + $scope.departCode
                                            + "&destCity=" + $scope.destCity + "&destCode=" + $scope.destCode
                                            + "&type=" + $scope.type
                                            + "&status=" + ($scope.destDate ? 1 : 0)
                                            + "&departDate=" + $scope.departDate + "&destDate=" + $scope.destDate;
                                        window.location.href = baseUrl + params;
                                    }

                                });
                            }
                            mfwPageEvent('flight', 'submit_order_failed', {    //简单参数统计
                                'buyer_name': $scope.buyer.buyer_name,
                                'origin_price': $scope.order_total_price,
                                'payment_price': $scope.getPaymentPrice(),
                                'errmsg': res.data.after.errmsg,
                                'errno': res.data.after.errno,
                                'pnrs': JSON.stringify($scope.aGetFormatOrderPnrs()),
                                'invoice_info': JSON.stringify($scope.needInvoice ? $scope.invoice_info : []),
                                'coupon_code': $scope.selectedCoupon.use ? $scope.selectedCoupon.coupon_code : ''
                            });
                            mfwPageEvent('flight', 'book_page', {
                                'name' : '国内机票下订单页',
                                'departDate' : $scope.departDate,
                                'destDate' : $scope.destDate,
                                'departCity' : $scope.departCity,
                                'departCode' : $scope.departCode,
                                'destCity' : $scope.destCity,
                                'destCode' : $scope.destCode,
                                'otaId' : $scope.otaId
                            });
                        }
                    });
            //临时下掉验证码
                }
            }).error(function (res) {
                mAlert("请求失败，请重试");
                return;
            })
            //临时下掉验证码
        };
    }]);
